package org.unt.logic;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Properties;

import org.apache.log4j.Logger;

public class Configurations {

	private static Logger logger = Logger.getLogger("ConfigurationLogic");

	public static String getMemoryInfo() {

		Runtime runtime = Runtime.getRuntime();

		String info = "Memory (in MB) <Free Total Max> " + //
				runtime.freeMemory() / 1024 / 1024 + "," + //
				runtime.totalMemory() / 1024 / 1024 + "," + //
				runtime.maxMemory() / 1024 / 1024;

		return info;
	}

	public static String classpath() {

		StringBuffer buffer = new StringBuffer();

		try {

			Properties props = System.getProperties();

			if (props == null) {
				return "Can't get CLASSPATH. Got null from 'System.getProperties()'";
			}

			String classpath = props.getProperty("java.class.path", null);

			if (classpath == null) {
				return "Can't get CLASSPATH. Got null from 'props.getProperty(\"java.class.path\", null)'";
			}

			buffer.append("CLASSPATH" + "\n");

			String[] paths = classpath.split(File.pathSeparator);
			for (int i = 0; i < paths.length; i++) {

				buffer.append(paths[i] + "\n");
			}

		} catch (NullPointerException e) {

			buffer.append(e.getMessage());

		} catch (Throwable t) {

			logger.error("Error getting CLASSPATH", t);
			buffer.append(t.getMessage());
			buffer.append((t.getCause() != null ? t.getCause().getMessage() : "t.getCause() is null") + "\n");
		}

		return buffer.toString();
	}

	public static URL getAbsolutePathJarFile(Class clazz) {

		if (clazz == null) {
			return null;
		}

		ProtectionDomain protectionDomain = clazz.getProtectionDomain();
		CodeSource codeSource = protectionDomain.getCodeSource();
		URL url = codeSource.getLocation();

		return url;
	}

	public static Properties load(String propsName) throws IOException {

		Properties props = new Properties();
		URL url = ClassLoader.getSystemResource(propsName);
		InputStream is = url.openStream();
		props.load(is);

		return props;
	}

	/**
	 * 
	 * @param filePath
	 *            Path should start by '/'
	 */
	public static File loadFileFromClasspath(String filePath) {

		URL url = Configurations.class.getResource(filePath);

		if (url == null) {
			throw new RuntimeException("Cannot find file '" + filePath
					+ "' from classpath. It should start by '/'. Check the file exists on classpath.");
		}

		return new File(url.getFile());
	}
}
